package snailAI.Controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.protobuf.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import snailAI.Entity.ChatMessage;
import snailAI.Service.UserService;
import snailAI.Utils.RedisUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisUtils redisUtils;
    @PostMapping("/login")
    public String login() {
        return null;
    }

    @PostMapping("/register")
    public String register() {
        return null;
    }


    //找到用户的对话列表ID。
    @PostMapping("/getMsgIDListByUid")
    public List<String> getMsgListByUid(@RequestParam(value = "uid", required = false, defaultValue = "1") int uid) {

        return userService.getMessageListIds(uid);

    }
    @PostMapping("/getMsgListByChatId")
    public List<ChatMessage>  getMsgListByChatId(@RequestBody Map<String,String> chatIdMap){
        String chatId=  chatIdMap.get("historyId");

        String jsonStr = (String) redisUtils.get("messageList" + chatId);

        if (jsonStr == null || jsonStr.isEmpty()) {
            return new ArrayList<>(); // 空列表兜底，避免空指针
        }

        // 2. 定义 Gson 解析的类型（因为是 List<ChatMessage>，需要用 TypeToken）
        Type type = new TypeToken<List<ChatMessage>>() {}.getType();
        Gson gson = new Gson();
        // 3. 解析 JSON 字符串为 List<ChatMessage>
        return gson.fromJson(jsonStr, type);

    }

}
